<template>
  <div class="uploader">
    <div @click="handleClick">
      <slot>
        <!-- <img src="" alt="1"/> -->
        <i></i>
      </slot>
    </div>
    <input class="upload-input" type="file" name="fileUpload" ref="input" @change="onFileChange"/>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
// import {isWeixin, isIOS} from '../utils/utils'
import {Loading} from 'element-ui'
// import {wxJsapi, wxDownImg} from '../service/api'
export default {
  props: {
    target: {
      type: String
    },
    action: {
      type: String,
      default: 'POST'
    },
    count: {
      type: Number,
      default: 0
    },
    max: {
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      file: null,
      loadingInstance: null
    }
  },
  computed: {
    ...mapGetters(['token'])
  },
  created () {

  },
  methods: {
    handleClick () {
      if (this.count > 0 && this.count >= this.max) {
        this.$message({
          message: `最多只能上传${this.max}张图片`

        })
        return
      }
      this.$refs.input.click()
    },
    emitter (event, data) {
      this.$emit(event, data)
    },
    uploadProgress (oEvent) {
      let vm = this
      if (oEvent.lengthComputable) {
        let percentComplete = Math.round(oEvent.loaded * 100 / oEvent.total)
        vm.emitter('progress', percentComplete)
      } else {
        vm.emitter('progress', false)
      }
    },
    onFileChange (e) {
      let vm = this
      if (!this.target || this.target === '') {
        console.log('Please provide the target url')
      } else if (!this.action || this.action === '') {
        console.log('Please provide file upload action ( POST / PUT )')
      } else if (this.action !== 'POST' && this.action !== 'PUT') {
        console.log('File upload component only allows POST and PUT Actions')
      } else {
        let files = e.target.files || e.dataTransfer.files
        if (!files.length) {
          return
        }
        this.file = files[0]
        console.log('this.file', this.file)
        let formData = new FormData()
        console.log('formData', formData)
        formData.append('file', this.file)
        let xhr = new XMLHttpRequest()
        console.log('xhr', xhr)
        xhr.open(this.action, this.target)
        // console.log('open', xhr.open(this.action, this.target))
        xhr.setRequestHeader('token', vm.token)
        // console.log('xhr.setRequestHeader', xhr.setRequestHeader('token', vm.token))
        xhr.onloadstart = function (e) {
          vm.loadingInstance = Loading.service({text: '上传中…'})
          vm.emitter('start', e)
        }
        xhr.onloadend = function (e) {
          vm.loadingInstance && vm.loadingInstance.close()
          let res = JSON.parse(e.currentTarget.response)
          console.log('res', res)
          if (res.code === 200) {
            vm.emitter('finish', res.value.url)
            console.log('resss', res.value.url)
          }
        }
        xhr.upload.onprogress = vm.uploadProgress
        xhr.send(formData)
        // console.log('xhr.send', xhr.send(formData))
      }
    }
  }
}
</script>

<style scoped lang="less">
.uploader{
  .upload-input{ display:none; }
  img{
    width:1.152rem;
    height:1.152rem;
    border-radius: .5rem;
  }
 }
</style>
